/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

function validateDate(inputText)
{
    var dateformat = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/;
    if (inputText.match(dateformat))
    {
        var pdate = inputText.split('/');

        var dd = parseInt(pdate[0]);
        var mm = parseInt(pdate[1]);
        var yy = parseInt(pdate[2]);
        var ListofDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
        if (mm === 1 || mm > 2)
        {
            if (dd > ListofDays[mm - 1])
            {
                return false;
            }
        }
        if (mm === 2)
        {
            var lyear = false;
            if ((!(yy % 4) && yy % 100) || !(yy % 400))
            {
                lyear = true;
            }
            if ((lyear === false) && (dd >= 29))
            {
                return false;
            }
            if ((lyear === true) && (dd > 29))
            {
                return false;
            }
        }
    }
    else
    {
        return false;
    }
    return true;
}

function dateToInt(date) {
    var date = date.split("/");
    var day = date[0];
    var month = date[1];
    var year = date[2];
    var ret = new Date();
    ret.setDate(day);
    ret.setMonth(month - 1);
    ret.setFullYear(year);
    return parseInt(ret.getTime() / 1000);
}

function addError(element, message) {
    var ni = element.parentNode;
    var newdiv = document.createElement('span');
    newdiv.setAttribute('class', 'error');
    newdiv.innerHTML = message;
    ni.appendChild(newdiv);
}

function addInfo(message) {
    var ni = document.getElementById("message");
    ni.innerHTML = message;
}

function addError2(message) {
    var ni = document.getElementById("message");
    ni.innerHTML = '';
    var newdiv = document.createElement('span');
    newdiv.setAttribute('class', 'error');
    newdiv.innerHTML = message;
    ni.appendChild(newdiv);
}

function removeError() {
    var paras = document.getElementsByClassName('error');
    var i = paras.length - 1;
    while (i >= 0) {
        paras[i].parentNode.removeChild(paras[i]);
        i--;
    }
}

function removeError2(element) {
    var nodes = element.parentNode.childNodes;
    for (var i = 0; i < nodes.length; i++) {
        if (nodes[i].className === 'error') {
            element.parentNode.removeChild(nodes[i]);
            break;
        }
    }
}

function bindKeyEnterEvent(event, callback) {
    if (event.keyCode === 13) {
        callback();
    }
}


function popup(message, confirmcallback, element) {
    var ni = document.getElementsByTagName('body')[0];
    var newdiv = document.createElement('div');
    newdiv.setAttribute('class', 'overlay');
    newdiv.setAttribute('id', 'overlayId');
    var childdiv = document.createElement('div');

    var title = document.createElement('h3');
    title.setAttribute("style", "margin: 0px 0px 0px 0px;padding: 0px 0px 0px 0px;");
    title.setAttribute("class", "heading");
    title.innerHTML = "Confirm";
    childdiv.appendChild(title);

    var line = document.createElement('hr');
    childdiv.appendChild(line);

    var pdiv = document.createElement('p');
    pdiv.innerHTML = message;
    childdiv.appendChild(pdiv);

    var span = document.createElement('span');

    var btnOk = document.createElement('a');
    btnOk.setAttribute('class', 'button-zm1');
    btnOk.setAttribute('style', 'margin-left:100px;');
    btnOk.innerHTML = "  &nbsp&nbsp&nbspOK&nbsp&nbsp&nbsp  ";


    span.appendChild(btnOk);

    var btnCancel = document.createElement('a');
    btnCancel.setAttribute('class', 'button-zm-cancel');
    btnCancel.innerHTML = "Cancel";


    span.appendChild(btnCancel);
    childdiv.appendChild(span);

    newdiv.appendChild(childdiv);
    ni.appendChild(newdiv);

    if (btnOk.addEventListener) {
        btnOk.addEventListener('click', function() {
            confirmcallback(element);
        }, false);
    } else if (btnOk.attachEvent) {
        btnOk.attachEvent('onclick', function() {
            confirmcallback(element);
        });
    }

    if (btnCancel.addEventListener) {
        btnCancel.addEventListener('click', function() {
            popUpCancel(element);
        }, false);
    } else if (btnCancel.attachEvent) {
        btnCancel.attachEvent('onclick', function() {
            popUpCancel(element);
        });
    }

    newdiv.style.visibility = (newdiv.style.visibility === "visible") ? "hidden" : "visible";
}

function info(message) {
    var ni = document.getElementsByTagName('body')[0];
    var newdiv = document.createElement('div');
    newdiv.setAttribute('class', 'overlay');
    newdiv.setAttribute('id', 'overlayId');

    var childdiv = document.createElement('div');

    var title = document.createElement('h3');
    title.setAttribute("style", "margin: 0px 0px 0px 0px;padding: 0px 0px 0px 0px;");
    title.innerHTML = "Information";
    childdiv.appendChild(title);

    var line = document.createElement('hr');
    childdiv.appendChild(line);

    var pdiv = document.createElement('p');
    pdiv.innerHTML = message;
    childdiv.appendChild(pdiv);

    var span = document.createElement('span');

    var btnCancel = document.createElement('a');
    btnCancel.setAttribute('class', 'button-zm1');
    btnCancel.innerHTML = "  &nbsp&nbsp&nbspOK&nbsp&nbsp&nbsp  ";


    span.appendChild(btnCancel);
    childdiv.appendChild(span);

    newdiv.appendChild(childdiv);
    ni.appendChild(newdiv);



    if (btnCancel.addEventListener) {
        btnCancel.addEventListener('click', function() {
            popUpCancel();
        }, false);
    } else if (btnCancel.attachEvent) {
        btnCancel.attachEvent('onclick', function() {
            popUpCancel();
        });
    }

    newdiv.style.visibility = (newdiv.style.visibility === "visible") ? "hidden" : "visible";
    childdiv.focus();
}

function error(message) {
    var ni = document.getElementsByTagName('body')[0];
    var newdiv = document.createElement('div');
    newdiv.setAttribute('class', 'overlay');
    newdiv.setAttribute('id', 'overlayId');

    var childdiv = document.createElement('div');

    var title = document.createElement('h3');
    title.setAttribute("style", "margin: 0px 0px 0px 0px;padding: 0px 0px 0px 0px;font-size:23px !important;color:red");
    title.innerHTML = "Error";
    childdiv.appendChild(title);

    var line = document.createElement('hr');
    childdiv.appendChild(line);

    var pdiv = document.createElement('p');
    pdiv.innerHTML = message;
    childdiv.appendChild(pdiv);

    var span = document.createElement('span');

    var btnCancel = document.createElement('a');
    btnCancel.setAttribute('class', 'button-zm1');
    btnCancel.innerHTML = "  &nbsp&nbsp&nbspOK&nbsp&nbsp&nbsp  ";


    span.appendChild(btnCancel);
    childdiv.appendChild(span);

    newdiv.appendChild(childdiv);
    ni.appendChild(newdiv);




    if (btnCancel.addEventListener) {
        btnCancel.addEventListener('click', function() {
            popUpCancel();
        }, false);
    } else if (btnCancel.attachEvent) {
        btnCancel.attachEvent('onclick', function() {
            popUpCancel();
        });
    }

    newdiv.style.visibility = (newdiv.style.visibility === "visible") ? "hidden" : "visible";
}
function popUpCancel(element) {
    if (undefined !== element && null !== element) {
        var nodeList = document.getElementsByName(element.name);
        for (var i = 0; i < nodeList.length; i++) {
            if (nodeList[i] !== element)
                nodeList[i].checked = element.checked;
        }
    }
    var el = document.getElementById("overlayId");
    el.parentNode.removeChild(el);
}

function addEdit(element) {
    var newEle = document.createElement('input');
    var nodeList = element.childNodes;
    var value;
    for (var i = 0; i < nodeList.length; i++) {
        if (nodeList[i].className === 'hidden-value') {
            value = nodeList[i].getAttribute('value');
        }
        if (nodeList[i].className === 'show-value') {
            nodeList[i].style.visibility = "hidden";
            nodeList[i].style.display = "none";
        }
    }
    if (element.getAttribute('param') === 'dateOfBirth') {
        newEle.setAttribute('class', 'input-value tcal');
        newEle.setAttribute('readonly', '');
    } else
        newEle.setAttribute('class', 'input-value');

    newEle.setAttribute("value", value);
    newEle.addEventListener('keydown', updateOnKeyDown, false);

    var yes = document.createElement('input');
    yes.setAttribute('type', 'button');
    yes.setAttribute('class', 'btnYes');
    var cancel = document.createElement('input');
    cancel.setAttribute('class', 'btnCancel');
    cancel.setAttribute('type', 'button');
    element.appendChild(newEle);
    element.appendChild(yes);
    element.appendChild(cancel);

    cancel.addEventListener('click', cancelEdit, false);
    yes.addEventListener('click', submitEdit, false);
    f_tcalInit();
    newEle.focus();
}

function updateOnKeyDown(event) {
    if (event.keyCode === 13) {
        submitEdit(event);
    }
    if (event.keyCode === 27) {
        cancelEdit(event);
    }
}

function submitEdit(event) {
    var parent = event.target.parentNode;
    var nodeList = parent.childNodes;
    var param = parent.getAttribute('param');
    var value;
    for (var i = 0; i < nodeList.length; i++) {
        if (hasClass(nodeList[i], 'input-value')) {
            if (param === 'dateOfBirth') {
                if (!validateDate(nodeList[i].value)) {
                    error('Invalid date');
                    return;
                }
                value = dateToInt(nodeList[i].value);
            } else {
                value = (nodeList[i].value);
            }
            nodeList[i].blur();
        }
        if (hasClass(nodeList[i], 'select-value')) {
            value = (nodeList[i].value);
            nodeList[i].blur();
        }
    }
    if (!validateProfileField(param, value))
        return;
    ajaxUpdateProfile(parent, param, value);
}

function ajaxUpdateProfile(parent, param, value) {
    var xmlhttp;
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState === 4 && xmlhttp.status === 200)
        {
            var result = JSON.parse(xmlhttp.responseText);
            if (result.STATUS === 'SUCCESS') {
                updateEdit(parent);
                var elememt;
                if (param === 'displayName') {
                    elememt = document.getElementById('head-name');
                    elememt.innerHTML = result.VALUE;
                }
                if (param === 'cityId') {
                    elememt = document.getElementById('head-city');
                    elememt.innerHTML = result.VALUE;
                }
                if (param === 'gender') {
                    elememt = document.getElementById('head-gender');
                    elememt.innerHTML = result.VALUE;
                }
                if (param === 'dateOfBirth') {
                    elememt = document.getElementById('head-age');
                    elememt.innerHTML = result.VALUE;
                }
                //info("Update successful.");

            }
            else {
                error(result.MESSAGE);
            }
        }
    };
    //xmlhttp.setRequestHeader("Content-Type", "application/son;charset=UTF-8");

    xmlhttp.open("POST", "/ajaxUpdate", true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send(param + '=' + encodeURIComponent(value));

}

function updateEdit(parent) {
    var value;
    var div;
    var nodeList = parent.childNodes;
    for (var i = 0; i < nodeList.length; i++) {

        if (hasClass(nodeList[i], 'input-value')) {
            value = nodeList[i].value;
            break;
        }
        if (hasClass(nodeList[i], 'select-value')) {
            value = nodeList[i].options[ nodeList[i].selectedIndex ].text;
            break;
        }
    }
    for (var i = 0; i < nodeList.length; i++) {

        if (hasClass(nodeList[i], 'select-value')) {
            nodeList[i].style.visibility = "hidden";
            nodeList[i].style.display = "none";
        }
        if (nodeList[i].className === 'hidden-value')
            nodeList[i].setAttribute('value', value);

        if (nodeList[i].className === 'show-value') {
            div = nodeList[i].style.visibility = "visible";
            nodeList[i].style.display = "inline-block";
            nodeList[i].innerHTML = value;
        }
    }
    var length = nodeList.length;
    for (var i = 0; i < length; i++) {
        if (nodeList[i].className === 'btnCancel') {
            parent.removeChild(nodeList[i]);
            i--;
            length--;
        }
        if (nodeList[i].className === 'btnYes') {
            parent.removeChild(nodeList[i]);
            i--;
            length--;
        }
        if (hasClass(nodeList[i], 'input-value')) {
            parent.removeChild(nodeList[i]);
            i--;
            length--;
        }
    }

    div.innerHTML = value;
}


function cancelEdit(event) {
    var value;
    var div;
    var parent = event.target.parentNode;
    var nodeList = parent.childNodes;
    for (var i = 0; i < nodeList.length; i++) {
        if (nodeList[i].className === 'hidden-value')
            value = nodeList[i].getAttribute('value');

        if (nodeList[i].className === 'show-value') {
            div = nodeList[i].style.visibility = "visible";
            nodeList[i].style.display = "inline-block";
        }
    }
    var length = nodeList.length;
    for (var i = 0; i < length; i++) {
        if (nodeList[i].className === 'btnCancel') {
            parent.removeChild(nodeList[i]);
            i--;
            length--;
        }
        if (nodeList[i].className === 'btnYes') {
            parent.removeChild(nodeList[i]);
            i--;
            length--;
        }
        if (hasClass(nodeList[i], 'input-value')) {
            parent.removeChild(nodeList[i]);
            i--;
            length--;
        }
    }

    div.innerHTML = value;
}


function hasClass(element, className) {
    return element.className && new RegExp("(^|\\s)" + className + "(\\s|$)").test(element.className);
}

function addSelect(element) {
    var nodeList = element.childNodes;

    for (var i = 0; i < nodeList.length; i++) {
        if (nodeList[i].className === 'show-value') {
            nodeList[i].style.visibility = "hidden";
            nodeList[i].style.display = "none";
        }
        if (hasClass(nodeList[i], 'select-value')) {
            nodeList[i].style.visibility = "visible";
            nodeList[i].style.display = "inline-block";
            nodeList[i].focus();
            nodeList[i].addEventListener('keydown', updateSelectOnKeyDown, false);
        }
    }

    var yes = document.createElement('input');
    yes.setAttribute('type', 'button');
    yes.setAttribute('class', 'btnYes');
    var cancel = document.createElement('input');
    cancel.setAttribute('class', 'btnCancel');
    cancel.setAttribute('type', 'button');
    element.appendChild(yes);
    element.appendChild(cancel);

    cancel.addEventListener('click', cancelSelect, false);
    yes.addEventListener('click', submitEdit, false);
}
function cancelSelect(event) {
    var parent = event.target.parentNode;
    var nodeList = parent.childNodes;
    for (var i = 0; i < nodeList.length; i++) {
        if (nodeList[i].className === 'show-value') {
            nodeList[i].style.visibility = "visible";
            nodeList[i].style.display = "inline-block";
        }
        if (hasClass(nodeList[i], 'select-value')) {
            nodeList[i].style.visibility = "hidden";
            nodeList[i].style.display = "none";
        }
    }
    var length = nodeList.length;
    for (var i = 0; i < length; i++) {
        if (nodeList[i].className === 'btnCancel') {
            parent.removeChild(nodeList[i]);
            i--;
            length--;
        }
        if (nodeList[i].className === 'btnYes') {
            parent.removeChild(nodeList[i]);
            i--;
            length--;
        }

    }
}

function updateSelectOnKeyDown(event) {
    if (event.keyCode === 13) {
        submitEdit(event);
    }
    if (event.keyCode === 27) {
        cancelSelect(event);
    }
}